package com.weibo;

import java.util.HashMap;
import java.util.List;

import weibo4android.Count;
import weibo4android.Status;
import weibo4android.User;
import weibo4android.WeiboException;

import android.app.Activity;

import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.weibo.aawbinterface.InitViews;
import com.weibo.aaweiboasync.AsyncDataLoader;
import com.weibo.aaweibobean.AccountInfo;
import com.weibo.aaweibobean.OAuthConstant;
import com.weibo.adapter.WeiboItemAdapter;
import com.weibo.data.DB;
import com.weibo.data.DBHandler;
import com.weibo.util.GetWeiboCount;
import com.weibo.util.WeiboLogin;

public class MainTabs extends Activity implements InitViews {

	RadioGroup radioGroup;
	RelativeLayout buttomMenu;
	PopupWindow bottomPop;
	RadioButton weibohomeRadio, messageRadio, selfinfoRadio, configRadio;

	private boolean isLoad, isMore;

	private Button titleCreateWeibo;// 写微博按钮
	private LinearLayout titlePoint;// 微博切换
	private TextView titleName;// 微博切换名称
	private ImageView titlePoint_nor;// 微博切换上三角
	private ImageView titlePoint_sel;// 微博切换下三角
	private Button titleRefresh;// 微博刷新按钮
	private ProgressBar titleProgress;// 刷新进度条
	private LinearLayout list_footer;// 微博最后一项，获取更多
	private TextView list_footer_more;// 微博最后一项，获取更多，(更多)
	private LinearLayout list_footer_loading;// 微博最后一项，获取更多，(进度)
	private ListView weiboList;// 所有微博View列表
	private List<Status> statusList;// 所有微博列表
	private List<Status> moreWeibo;// 获取更多的微博
	private HashMap<Long, Count> counts;// 每条微博转为HashMap<微博ID,内容>
	private int foot;// 获取更多微博前的微博数，包括“更多”一项
	private String lastId;// 最后一条微博的ID(Long类型)
	private Gallery homegallery;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.maintabs);
		mainInit();
	}

	private void mainInit() {

		oAuth();// 验证用户信息
		beanInit();// 初始化参数
		frameInit();// 初始化外框
		homePageInit();// 初始化首页
	}

	private void oAuth() {
		Uri uri = this.getIntent().getData();
		if (uri == null) { // 通过本地保存的帐号信息登录
			WeiboLogin.login(this.getIntent().getExtras());
		} else {
			OAuthConstant oAuthConstant = OAuthConstant.getInstance();
			User user = WeiboLogin.getUser(uri, oAuthConstant);
			if (user != null) {
				WeiboLogin.saveAccounts(getSharedPreferences(AccountInfo.ACCOUNTS, MODE_PRIVATE),
						user, oAuthConstant);
				WeiboToast.show(this, "保存用户信息成功!");
			} else {
				WeiboToast.show(this, "无法获取用户信息，请重新授权!");
			}
		}
	}

	private void beanInit() {
		this.isLoad = false;
		this.isMore = false;
	}

	private void resetButtonAlpha(int radio) {
	weibohomeRadio.getCompoundDrawables()[1].setAlpha(100);
		messageRadio.getCompoundDrawables()[1].setAlpha(100);
		selfinfoRadio.getCompoundDrawables()[1].setAlpha(100);
		configRadio.getCompoundDrawables()[1].setAlpha(100);
		switch (radio) {
		case 0:
			weibohomeRadio.getCompoundDrawables()[1].setAlpha(255);
			break;
		case 1:
			messageRadio.getCompoundDrawables()[1].setAlpha(255);
			break;
		case 2:
			selfinfoRadio.getCompoundDrawables()[1].setAlpha(255);
			break;
		case 3:
			configRadio.getCompoundDrawables()[1].setAlpha(255);
			break;
		default:
			break;
		}
	
	}

	private void frameInit() {
		View popupView = this.getLayoutInflater().inflate(R.layout.popupwindow, null);
		radioGroup = (RadioGroup) popupView.findViewById(R.id.mainTabs_radioGroup);
		bottomPop = new PopupWindow(popupView, 480, 90);
		bottomPop.setAnimationStyle(R.style.AnimationPreview);
		bottomPop.setBackgroundDrawable(new ColorDrawable());
		weibohomeRadio = (RadioButton) popupView.findViewById(R.id.mainTabs_radio_weibohome);
		messageRadio = (RadioButton) popupView.findViewById(R.id.mainTabs_radio_message);
		selfinfoRadio = (RadioButton) popupView.findViewById(R.id.mainTabs_radio_selfinfo);
		configRadio = (RadioButton) popupView.findViewById(R.id.mainTabs_radio_config);
		weibohomeRadio.setChecked(true);
		resetButtonAlpha(0);
		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.mainTabs_radio_weibohome:
					resetButtonAlpha(0);

					break;
				case R.id.mainTabs_radio_message:
					resetButtonAlpha(1);

					break;
				case R.id.mainTabs_radio_selfinfo:
					resetButtonAlpha(2);

					break;
				case R.id.mainTabs_radio_config:
					resetButtonAlpha(3);

					break;

				default:
					break;
				}
			}
		});

	}

	private void homePageInit() {
		getViews();
		setViews();
		setListeners();
		new AsyncDataLoader(asyncLocalCallback).execute();
	}

	private void weiboControl(String mode) {
		if (mode == "more") {
			if (isMore) {
				WeiboToast.show(MainTabs.this, "正在获取更多微薄，请稍候...");
			} else {
				isMore = true;
				new AsyncDataLoader(asyncMoreCallback).execute();
			}
		} else if (mode == "load") {
			if (isLoad) {
				WeiboToast.show(MainTabs.this, "正在获取新微薄，请稍候...");
			} else {
				isLoad = true;
				new AsyncDataLoader(asyncLoadCallback).execute();
			}
		}
	}

	/**
	 * 异步加载服务器上的微博数据的监听器
	 */
	private AsyncDataLoader.Callback asyncLoadCallback = new AsyncDataLoader.Callback() {

		@Override
		public void onPrepare() {
			titleRefresh.setVisibility(View.GONE);
			titleProgress.setVisibility(View.VISIBLE);
		}

		@Override
		public void onStart() {
			try {
				statusList = Sina.getInstance().getWeibo().getFriendsTimeline();
				counts = GetWeiboCount.getCounts(statusList);
				saveData(statusList, counts);
			} catch (WeiboException e) {
				e.printStackTrace();
				Log(e.toString());
			}
		}

		@Override
		public void onFinish() {
			WeiboItemAdapter adapter = new WeiboItemAdapter(MainTabs.this, statusList, counts);
			weiboList.setAdapter(adapter);
			homegallery.setAdapter(adapter);
			titleProgress.setVisibility(View.GONE);
			titleRefresh.setVisibility(View.VISIBLE);
			isLoad = false;
		}
	};
	/**
	 * 异步加载本地的微博数据的监听器
	 */
	private AsyncDataLoader.Callback asyncLocalCallback = new AsyncDataLoader.Callback() {

		@Override
		public void onPrepare() {
			titleRefresh.setVisibility(View.GONE);
			titleProgress.setVisibility(View.VISIBLE);
		}

		@Override
		public void onStart() {
			statusList = new DBHandler(MainTabs.this).getStatus();
			counts = new DBHandler(MainTabs.this).getCounts();
		}

		@Override
		public void onFinish() {
			WeiboItemAdapter adapter = new WeiboItemAdapter(MainTabs.this, statusList, counts);
			weiboList.setAdapter(adapter);
			homegallery.setAdapter(adapter);
			titleProgress.setVisibility(View.GONE);
			titleRefresh.setVisibility(View.VISIBLE);
		}
	};

	/**
	 * 异步加载更多的微博数据的监听器
	 */
	private AsyncDataLoader.Callback asyncMoreCallback = new AsyncDataLoader.Callback() {

		@Override
		public void onPrepare() {
			list_footer_more.setVisibility(View.GONE);
			list_footer_loading.setVisibility(View.VISIBLE);
			titleRefresh.setVisibility(View.GONE);
			titleProgress.setVisibility(View.VISIBLE);
			lastId = String.valueOf(statusList.get(statusList.size() - 1).getId());
			foot = weiboList.getCount();
		}

		@Override
		public void onStart() {

			try {
				moreWeibo = Sina.getInstance().getWeibo().getFriendsTimelineMax(lastId);
				counts = GetWeiboCount.appendCounts(moreWeibo, counts);
			} catch (WeiboException e) {
				e.printStackTrace();
			}

		}

		@Override
		public void onFinish() {
			statusList.addAll(moreWeibo);
			WeiboItemAdapter adapter = new WeiboItemAdapter(MainTabs.this, statusList, counts);
			weiboList.setAdapter(adapter);
			homegallery.setAdapter(adapter);
			weiboList.setSelection(foot);
			list_footer_more.setVisibility(View.VISIBLE);
			list_footer_loading.setVisibility(View.GONE);
			titleRefresh.setVisibility(View.VISIBLE);
			titleProgress.setVisibility(View.GONE);
			isMore = false;
		}
	};

	/**
	 * 保存微博数据
	 */
	private void saveData(List<Status> status, HashMap<Long, Count> counts) {

		DBHandler dbHandler = new DBHandler(MainTabs.this);
		dbHandler.clearTable(DB.HOME_TABLE);
		if (status.size() > 20) { // 只保存前20项
			status = status.subList(0, 19);
		}
		for (int i = 0; i < status.size(); i++) {
			dbHandler.save(status.get(i), counts.get(status.get(i).getId()));
		}
	}

	/**
	 * 发表新微博
	 */
	private void createWeibo() {
		Sina.getInstance().updateWeibo(this);
	}

	@Override
	public void getViews() {

		titleCreateWeibo = (Button) findViewById(R.id.titlebar_createWeibo);// 写微博按钮

		titlePoint = (LinearLayout) findViewById(R.id.titlebar_point);// 微博切换按钮
		titleName = (TextView) titlePoint.findViewById(R.id.titlebar_name);// 微博切换按钮中的微博名
		titlePoint_nor = (ImageView) titlePoint.findViewById(R.id.titlebar_point_nor);// 微博切换按钮上三角
		titlePoint_sel = (ImageView) titlePoint.findViewById(R.id.titlebar_point_sel);// 微博切换按钮下三角
		titleRefresh = (Button) findViewById(R.id.titlebar_refresh);// 微博刷新按钮
		titleProgress = (ProgressBar) findViewById(R.id.titlebar_progress);// 微博刷新按钮按下后显示的进度

		weiboList = (ListView) findViewById(R.id.home_weiboList);// 微博列表
		homegallery = (Gallery) findViewById(R.id.gallery);

		list_footer = (LinearLayout) getLayoutInflater().inflate(R.layout.list_footer, null);// 微博列表最后一个view（更多）
		list_footer_more = (TextView) list_footer.findViewById(R.id.footer_more);// （更多）按钮
		list_footer_loading = (LinearLayout) list_footer.findViewById(R.id.footer_loading);// 正在获取更多view
	}

	@Override
	public void setViews() {
		titleCreateWeibo.setVisibility(View.VISIBLE);
		titleName.setVisibility(View.VISIBLE);
		titlePoint.setClickable(true);
		titlePoint_nor.setVisibility(View.VISIBLE);
		titleRefresh.setVisibility(View.VISIBLE);
		try {
			titleName.setText(Sina.getInstance().getWeibo().verifyCredentials().getName());
		} catch (WeiboException e) {
			e.printStackTrace();
		}
		weiboList.addFooterView(list_footer);
	}

	@Override
	public void setListeners() {
		titleCreateWeibo.setOnClickListener(clickListener);
		titlePoint.setOnClickListener(clickListener);
		titleRefresh.setOnClickListener(clickListener);
		weiboList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				if (arg2 == (weiboList.getCount() - 1)) { // 列表最后一项：显示更多微博
					weiboControl("more");
					return;
				}
				Sina.getInstance().goToDetail(MainTabs.this, statusList.get(arg2));
			}
		});
	}

	private OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.titlebar_createWeibo:
				createWeibo();
				break;
			case R.id.titlebar_refresh:
				weiboControl("load");
				break;
			default:
				break;
			}
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			if (bottomPop.isShowing()) {
				bottomPop.dismiss();
			} else
				bottomPop.showAtLocation(this.findViewById(R.id.home_listview), Gravity.BOTTOM, 0,
						-74);
			return false;
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (!bottomPop.isShowing()) {
				return super.onKeyDown(keyCode, event);
			} else
				bottomPop.dismiss();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			bottomPop.dismiss();
		}
		return super.dispatchTouchEvent(ev);
	}

	private void Log(String string) {
		Log.v("weibo", "MainTabs--" + string);
	}
}